package com.demo.web.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

//替换spring security默认的表单登录参数提取
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    //继承并重写这个方法
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //判断是否post请求
        if(!request.getMethod().equals("POST")){
            //身份认证服务异常
          throw new AuthenticationServiceException("不支持当前认证方式，请以post方式登录");
        }
        //判断是否json或者加了utf格式的
        if(request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)||request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)){
          //代表是json格式的 接下来取数据 获取输入流转化为map 取账户名密码
            try {
                Map<String,String> userinfo=new ObjectMapper().readValue(request.getInputStream(),Map.class);
                String username=userinfo.get(getUsernameParameter());
                String password=userinfo.get(getPasswordParameter());
                UsernamePasswordAuthenticationToken token=new UsernamePasswordAuthenticationToken(username,password);
                setDetails(request,token);
                //认证
              return this.getAuthenticationManager().authenticate(token);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


        return super.attemptAuthentication(request, response);
    }
}
